﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Service.Framework.Packet;
using Service.Framework.Utils;

namespace Service.Core.Filters;

/// <summary>
/// Api 结果返回包装器
/// </summary>
public class ApiResultFilter : IAsyncResultFilter, IOrderedFilter
{
    public int Order => 0; // 先执行

    public ApiResultFilter()
    {
    }

    /// <summary>
    /// 结果 返回前
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        var endpoint = context.HttpContext.GetEndpoint();
        if (endpoint?.Metadata.GetMetadata<IgnoreResultFilterAttribute>() != null)
        {
            await next.Invoke();
            return;
        }
        if (context.Result != null && !context.HttpContext.Response.Headers["Content-Disposition"].ToString().StartsWith("attachment; filename="))
        {
            if (context.Result is ObjectResult)
            {

                var result = context.Result as ObjectResult;
                if (typeof(bool).Equals(result.DeclaredType))
                {
                    context.Result = new JsonResult(R.Ok("success", (bool)result.Value ? "1" : "0"));
                }
                else
                {
                    context.Result = new JsonResult(R.Ok("success", result?.Value));
                }

            }
            else if (context.Result is ContentResult)
            {
                var result = context.Result as ContentResult;
                context.Result = new JsonResult(R.Ok("success", result?.Content));
            }
            else if (context.Result is EmptyResult)
            {
                context.Result = new JsonResult(R.Ok("success", ""));
            }

        }
        await next.Invoke();
    }

}